package com.example.origin.flowable.controller;

import com.example.origin.flowable.entity.GroupUsersDto;
import com.example.origin.flowable.utils.JsonPrintUtil;
import org.apache.commons.io.IOUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.identitylink.api.IdentityLinkInfo;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("containGateway")
public class ContainGatewayController {

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IdentityService identityService;


    private static final String BPMN_CONTAIN_GATEWAY ="bpmn/包容网关.bpmn20.xml";

    @GetMapping("deployFlow")
    public String deployFlow() {
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource(BPMN_CONTAIN_GATEWAY).name("候选人组流程图").deploy();//部署的方法
        return jsonStr(deploy);
    }

    @GetMapping("delDeployFlow")
    public String delDeployFlow(@RequestParam String deploymentId) {
        repositoryService.deleteDeployment(deploymentId);
        return "";
    }

    private String jsonStr(Object deploy){
        return JsonPrintUtil.jsonStr(deploy);
    }

    private <T> String jsonStr(List<T> list){
        return JsonPrintUtil.jsonStr(list);
    }



    @GetMapping("findDeployFlows")
    public String findDeployFlows() {
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionId().desc().list();
        return jsonStr(list);
    }


    // ACT_RU_IDENTITYLINK
    @GetMapping("startFlow")
    public String startFlow(@RequestParam String processDefId) {
         ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefId);
        return jsonStr(processInstance);
    }
    @GetMapping("delFlow")
    public String delFlow(@RequestParam String processId) {
        runtimeService.deleteProcessInstance(processId,"not userd");
        return "";
    }

    // act-ru-task
    @GetMapping("findUndoTasks")
    public String findUndoTasks(@RequestParam String processId) {
        //act_ru_task
        List<Task> list = taskService.createTaskQuery().processInstanceId(processId)
                .list();
        return jsonStr(list);
    }

    @GetMapping("setAssignee")
    public String setAssignee(@RequestParam String taskId,@RequestParam String assignee) {
        Task task = taskService.createTaskQuery()
                .taskId(taskId).singleResult();
        taskService.setAssignee(task.getId(),assignee);
        return "";
    }


    // act-ru-task
    @GetMapping("completeTask")
    public String completeTask(@RequestParam String taskId,@RequestParam String assignee,@RequestParam Integer num) {
        Task task = taskService.createTaskQuery().taskId(taskId).taskAssignee(assignee).singleResult();
        if (task!=null) {
            Map<String,Object> map = new HashMap<>();
            map.put("num",num);
            //完成任务的中批。根解任务的ID
            taskService.complete(taskId,map);
            return "success";
        }
        return "error";
    }

    @GetMapping("findHistorys")
    public String findHistorys(@RequestParam String processId) {
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processId).orderByProcessInstanceEndTime().desc().list();
        return jsonStr(list);
    }


    @Autowired
    private HistoryService historyService;

    @GetMapping(value = "/getProcessDiagram")
    public void getProcessDiagram(@RequestParam String processId,HttpServletResponse httpServletResponse) {

//        // 根据任务 ID 获取流程实例 ID
//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
//        String processInstanceId = task.getProcessInstanceId();

        // 根据流程实例获取流程图
        // 流程定义 ID
        String processDefinitionId;

        // 查看完成的进程中是否存在此进程
        long count = historyService.createHistoricProcessInstanceQuery().finished().processInstanceId(processId).count();
        if (count > 0) {
            // 如果流程已经结束，则得到结束节点
            HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();

            processDefinitionId = pi.getProcessDefinitionId();
        } else {// 如果流程没有结束，则取当前活动节点
            // 根据流程实例ID获得当前处于活动状态的ActivityId合集
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        }
        List<String> highLightedActivitis = new ArrayList<>();

        // 获得活动的节点
        List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId).orderByHistoricActivityInstanceStartTime().asc().list();

        for (HistoricActivityInstance tempActivity : highLightedActivitList) {
            String activityId = tempActivity.getActivityId();
            highLightedActivitis.add(activityId);
        }

        List<String> flows = new ArrayList<>();
        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        ProcessEngineConfiguration processEngineConfig = processEngine.getProcessEngineConfiguration();

        ProcessDiagramGenerator diagramGenerator = processEngineConfig.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "bmp", highLightedActivitis, flows, processEngineConfig.getActivityFontName(),
                processEngineConfig.getLabelFontName(), processEngineConfig.getAnnotationFontName(), processEngineConfig.getClassLoader(), 1.0, true);

        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }
    }





}
